package com.easydata.agent.xxljob;

import com.alibaba.fastjson2.JSON;
import com.easydata.agent.core.entity.TaskDefinition;
import com.easydata.agent.service.TaskService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.executor.XxlJobExecutor;
import com.xxl.job.core.handler.IJobHandler;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class XxlJobTaskHandler extends IJobHandler {
    @Autowired
    TaskService taskService;

    @PostConstruct
    void postConstruct() {
        XxlJobExecutor.registJobHandler("task", this);
    }

    @Override
    public void execute() throws Exception {
        log.info("task execute thread: " + String.valueOf(Thread.currentThread().threadId()));
        log.info("job id: " + XxlJobHelper.getJobId());
        log.info("param: " + XxlJobHelper.getJobParam());
        TaskDefinition taskDefinition = JSON.parseObject(XxlJobHelper.getJobParam(), TaskDefinition.class);
        taskDefinition.setId(String.valueOf(XxlJobHelper.getJobId()));
        var task = taskService.createTask(taskDefinition);

        try {
            taskService.prepareTask(task);
            taskService.executeTask(task);
        } catch (Exception ex) {
            task.cleanup();
            throw ex;
        }
    }
}
